<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <!-- 搜索 -->
      <el-input
        v-model="query.desensitizeField"
        clearable
        size="small"
        placeholder="请输入脱敏字段"
        style="width:200px"
        class="filter-item"
      />
      <template>
        <el-select
          v-model="query.functionId"
          clearable
          filterable
          placeholder="请选择脱敏函数搜索"
          style="width: 170px"
        >
          <el-option
            v-for="item in functionList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template>
      <rrOperation :crud="crud" />
      <div style="margin-left: 5px;display: inline-block">
        <el-button
          class="filter-item"
          icon="el-icon-plus"
          type="primary"
          @click="initAllFunctionList();addDesensitizeFieldFlag = true"
        >新增</el-button>
        <el-button
          v-if="crud.optShow.del"
          slot="reference"
          v-permission="permission.del"
          class="filter-item"
          type="danger"
          icon="el-icon-delete"
          :loading="crud.delAllLoading"
          :disabled="crud.selections.length === 0"
          @click="toDelete(crud.selections)"
        >删除
        </el-button>
      </div>
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      border
      max-height="300px"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column
        type="selection"
        width="40"
      />
      <el-table-column
        label="脱敏函数说明"
        prop="functionExplain"
        width="200px"
      />
      <el-table-column
        label="脱敏函数名称"
        prop="functionName"
        width="180px"
      />
      <el-table-column
        label="脱敏字段"
        prop="desensitizeField"
        width="130px"
      />
      <el-table-column
        label="脱敏函数样例"
        prop="desensitizeExample"
      />
      <el-table-column
        label="更新人"
        prop="createBy"
        width="100px"
      />
      <el-table-column
        label="更新时间"
        prop="createTime"
        width="150px"
      />
    </el-table>
    <div style=" float: right;">
      <!--分页组件-->
      <pagination />
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :before-close="cancelCU"
      :visible.sync="addDesensitizeFieldFlag"
      title="新增脱敏字段"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :inline="true"
        label-width="120px"
      >
        <el-form-item
          label="脱敏字段"
          prop="fieldName"
        >
          <el-input
            v-model="form.fieldName"
            clearable
            size="small"
            style="width: 300px"
            placeholder="请输入脱敏字段"
          />
        </el-form-item>
        <el-form-item
          label="脱敏函数"
          prop="functionId"
        >
          <el-select
            v-model="form.functionId"
            :disabled="form.fieldName === null"
            style="width: 300px"
            @change="functionNameChange"
          >
            <el-option
              v-for="item in desensitizationFuncationList"
              :key="item.id"
              :label="item.functionExplain"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="脱敏函数样例"
          prop="desensitizeFunction"
        >
          <el-input
            v-model="form.desensitizeFunction"
            clearable
            size="small"
            :disabled="form.fieldName === null"
            style="width: 300px"
            type="textarea"
            :rows="3"
            placeholder="请输入脱敏函数描述"
          />
        </el-form-item>
        <div
          class="dialog-footer"
          style="width:100%;text-align: center"
        >
          <el-button @click="addDesensitizeFieldFlag = false">关 闭</el-button>
          <el-button
            :loading="this.submitAddDesensitizeFieldFlag === true"
            type="primary"
            @click="submitFunction()"
          >保 存</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import desensitizeFunctionApi from '@/api/dashboard/desensitizeFunction'
import CRUD, {presenter, header, form, crud} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import {validateChinese, validateCode} from '@/utils/validate'
import desensitizeFieldMapApi from '@/api/dashboard/desensitizationFieldMap'
import desensitizationFieldsTaskApi from '@/api/dashboard/desensitizationFieldsTask'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '数据脱敏函数配置',
  url: 'api/desensitizeFieldMap/page',
  crudMethod: {...desensitizeFieldMapApi}
})
const defaultForm = {
  id: null,
  functionId: null,
  dbName: null,
  tableName: null,
  fieldName: null,
  desensitizeFunction: null
}
export default {
  name: 'DataDesensitizationRules',
  components: { rrOperation, pagination },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    var validateFunctionExplain = (rule, value, callback) => {
      if (value != null && value !== '') {
        const params = {functionExplain: value, page: 10000000}
        desensitizeFunctionApi.findListByPage(params).then(res => {
          if (res.totalElements > 0) {
            res.content.forEach(item => {
              let isExist = false
              if (value === item.functionExplain) {
                isExist = true
              }
              if (isExist) {
                callback(new Error('该函数说明已存在!'))
              } else {
                callback()
              }
            })
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    }
    var validateFunctionName = (rule, value, callback) => {
      if (value != null && value !== '') {
        const params = {functionName: value, page: 10000000}
        desensitizeFunctionApi.findListByPage(params).then(res => {
          if (res.totalElements > 0) {
            res.content.forEach(item => {
              let isExist = false
              if (value === item.functionName) {
                isExist = true
              }
              if (isExist) {
                callback(new Error('该函数名称已存在!'))
              } else {
                callback()
              }
            })
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    }
    return {
      functionList: [],
      desensitizationFuncationList: [],
      simpleFlag: false,
      simpleDataLoading: false,
      addDesensitizeFieldFlag: false,
      submitAddDesensitizeFieldFlag: false,
      permission: {
        add: ['admin', 'scriptPack:add'],
        del: ['admin', 'scriptPack:del']
      },
      rules: {
        functionExplain: [
          {required: true, message: '请输入脱敏函数说明', trigger: 'blur'},
          {validator: validateChinese, trigger: 'blur'},
          {validator: validateFunctionExplain, trigger: 'blur'}
        ],
        functionName: [
          {required: true, message: '请输入脱敏函数名称', trigger: 'blur'},
          {validator: validateCode, trigger: 'blur'},
          {validator: validateFunctionName, trigger: 'blur'}
        ],
        functionDetails: [
          {required: true, message: '请输入脱敏函数描述', trigger: 'blur'}
        ]
      },
      tableList: []
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.initFunctionList()
      this.initAllFunctionList()
    },
    // 初始化获取已配置的脱敏函数列表
    initFunctionList() {
      desensitizeFunctionApi.findList().then(res => {
        res.forEach((item) => {
          const obj = {
            value: item.id,
            label: item.functionName
          }
          this.functionList.push(obj)
        })
      })
    },
    // 初始化获取所有的脱敏函数列表
    initAllFunctionList() {
      const param = {size: 10000000}
      desensitizeFunctionApi.findListByPage(param).then(res => {
        if (res.totalElements > 0) {
          this.desensitizationFuncationList = res.content
        }
      })
    },
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
    },
    functionNameChange(functionId) {
      let functionObject = null
      this.desensitizationFuncationList.forEach(item => {
        if (functionId === item.id) {
          functionObject = JSON.parse(JSON.stringify(item))
        }
      })
      this.form.desensitizeFunction = functionObject.functionDetails.replace('field_name', this.form.fieldName)
    },
    submitFunction() {
      this.submitAddDesensitizeFieldFlag = true
      desensitizationFieldsTaskApi.add(this.form).then(res => {
        this.submitAddDesensitizeFieldFlag = false
        this.addDesensitizeFieldFlag = false
        this.crud.refresh()
      })
    },
    cancelCU() {
      this.simpleFlag = false
      this.addDesensitizeFieldFlag = false
    }
  }
}
</script>
<style scoped>

</style>
